<template>
  <div class="setup-user-container">
    <table-bar @search="handleSearch" @reset="handleReset" />

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form inline :model="searchData">
        <el-form-item label="搜索字段">
          <el-input v-model="searchData.search" placeholder="请输入搜索内容" style="width: 200px" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchData.state" placeholder="请选择" style="width: 120px">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddUser">新增用户</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <art-table
      :data="tableData"
      :loading="loading"
      :pagination="true"
      :total="total"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      highlight-current-row
      show-header-background
    >
      <el-table-column prop="username" label="用户名" min-width="150" />
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="sex" label="性别" min-width="80" align="center">
        <template #default="scope">
          <span v-if="scope.row.sex === '男'">男</span>
          <span v-else-if="scope.row.sex === '女'">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" min-width="120" />
      <el-table-column prop="email" label="邮箱" min-width="150" />
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column prop="state" label="状态" min-width="80" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            @click="handleStatusChange(scope.row)"
            :disabled="scope.row.platformUserId === 1"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="table-actions">
            <button-table type="edit" @click="handleEditUser(scope.row)" />
            <el-popconfirm
              title="确认删除此用户吗？"
              @confirm="handleDeleteUser(scope.row.platformUserId)"
            >
              <template #reference>
                <button-table
                  type="delete"
                  :disabled="scope.row.platformUserId === 1"
                  @click.stop="() => {}"
                />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </art-table>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="40%"
      center
      :close-on-click-modal="false"
      @closed="onDialogClosed"
    >
      <el-form ref="userFormRef" :model="userForm" label-width="80px" :rules="userFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" placeholder="请选择角色" multiple>
            <el-option
              v-for="role in roleList"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            show-password
            :placeholder="'请输入密码'"
          />
          <div v-if="isEdit" style="font-size: 12px; color: #999; margin-top: 5px"> </div>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-switch v-model="userForm.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { ApiStatus } from '@/utils/http/status'

  // API 导入
  import { SetupService } from '@/api/setupApi'

  // 搜索数据
  const searchData = reactive({
    // 使用search字段代替username，符合后端要求
    search: '',
    // 使用null作为初始值，后续处理为数字类型
    state: null,
    page: 1,
    pageSize: 10
  })

  // 表格数据
  const tableData = ref<any[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 角色列表
  const roleList = ref<any[]>([])

  // 对话框数据
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const submitLoading = ref(false)
  const userFormRef = ref<FormInstance | null>(null)

  // 用户表单
  const userForm = reactive({
    platformUserId: 0,
    username: '',
    name: '',
    sex: '',
    phone: '',
    email: '',
    // 使用roleIds代替ids，符合后端要求
    roleIds: [],
    roles: [],
    password: '',
    // state字段使用数字类型，符合后端要求
    state: 1
  })

  // 表单验证规则
  const userFormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
      {
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: '请输入正确的邮箱地址',
        trigger: 'blur'
      }
    ],
    // 使用roleIds代替ids，符合后端要求
    roleIds: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ],
    password: [
      { required: !isEdit.value, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
  }

  // 初始化数据
  onMounted(() => {
    getUsersList()
    getRolesList()
  })

  // 获取用户列表
  const getUsersList = async () => {
    loading.value = true
    try {
      // 构建符合后端要求的参数
      const queryParams = {
        // 使用search字段代替username
        search: searchData.search,
        // 确保state为数字类型，或undefined（当为null或空字符串时不传递）
        state: searchData.state !== null && searchData.state !== '' ? Number(searchData.state) : undefined,
        page: searchData.page,
        pageSize: searchData.pageSize
      }
      
      const res = await SetupService.userGetAll(queryParams)
      if (res.code === ApiStatus.success) {
        // 修复类型问题：根据实际返回的数据结构调整
        if (Array.isArray(res.data)) {
          // 如果res.data直接是数组
          tableData.value = res.data
          total.value = res.data.length
        } else if (res.data && typeof res.data === 'object' && 'list' in res.data) {
          // 如果res.data包含list字段（分页结构）
          const pageData = res.data as { list: any[]; total?: number }
          tableData.value = pageData.list || []
          total.value = pageData.total || 0
        } else {
          // 其他情况，初始化为空数组
          tableData.value = []
          total.value = 0
        }
      } else {
        ElMessage.error(res.message || '获取用户列表失败')
        tableData.value = []
        total.value = 0
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
      console.error(error)
      tableData.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 获取角色列表
  const getRolesList = async () => {
    try {
      const res = await SetupService.roleGetAll({ page: 1, pageSize: 100 })
      if (res.code === ApiStatus.success) {
        // 修复类型问题：根据实际返回的数据结构调整
        if (Array.isArray(res.data)) {
          // 如果res.data直接是数组
          roleList.value = res.data
        } else if (res.data && typeof res.data === 'object' && 'list' in res.data) {
          // 如果res.data包含list字段（分页结构）
          const pageData = res.data as { list: any[] }
          roleList.value = pageData.list || []
        } else {
          // 其他情况，初始化为空数组
          roleList.value = []
        }
      } else {
        ElMessage.error(res.message || '获取角色列表失败')
        roleList.value = []
      }
    } catch (error) {
      ElMessage.error('获取角色列表失败')
      console.error(error)
      roleList.value = []
    }
  }

  // 处理搜索
  const handleSearch = () => {
    searchData.page = 1
    getUsersList()
  }

  // 处理重置
  const handleReset = () => {
    searchData.search = ''
    searchData.state = null
    searchData.page = 1
    searchData.pageSize = 10
    getUsersList()
  }

  // 处理分页大小变化
  const handleSizeChange = (size: number) => {
    searchData.pageSize = size
    getUsersList()
  }

  // 处理当前页变化
  const handleCurrentChange = (current: number) => {
    searchData.page = current
    getUsersList()
  }

  // 新增用户
  const handleAddUser = () => {
    isEdit.value = false
    // 重置表单
    Object.assign(userForm, {
      platformUserId: 0,
      username: '',
      name: '',
      sex: '',
      phone: '',
      email: '',
      // 使用roleIds代替ids，符合后端要求
      roleIds: [],
      roles: [],
      password: '',
      // state字段使用数字类型，符合后端要求
      state: 1
    })
    // 清空表单验证
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }
    dialogVisible.value = true
  }

  // 编辑用户
  const handleEditUser = async (row: any) => {
    isEdit.value = true
    // 清空表单验证
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }

    try {
      // 获取用户详情
      const res = await SetupService.userGetById({ platformUserId: row.platformUserId })
      if (res.code === ApiStatus.success) {
        const userInfo = res.data || {}
        // 获取角色ID数组
        const roleIdsArray = userInfo.roles || userInfo.ids || []
        // 提取纯数字ID，过滤掉对象格式的元素，确保只包含数字类型
        const pureRoleIds = roleIdsArray
          .map(id => {
            // 如果是对象格式，尝试获取其roleId属性
            if (typeof id === 'object' && id !== null && 'roleId' in id) {
              return Number(id.roleId)
            }
            // 如果是数字或字符串，直接转换为数字
            return Number(id)
          })
          // 过滤掉非数字值
          .filter(id => !isNaN(id) && isFinite(id))
        
        // 使用Set进行去重，确保roleIds数组中没有重复的数字ID
        const uniqueRoleIds = Array.from(new Set(pureRoleIds))
        
        // 填充表单数据
        Object.assign(userForm, {
          platformUserId: userInfo.platformUserId,
          username: userInfo.username,
          name: userInfo.name,
          sex: userInfo.sex || '',
          phone: userInfo.phone,
          email: userInfo.email,
          // 使用纯数字且去重后的roleIds数组
          roleIds: uniqueRoleIds,
          password: userInfo.password || '',
          // 确保state为数字类型
          state: userInfo.state !== undefined ? Number(userInfo.state) : 1
        })
        dialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取用户详情失败')
      }
    } catch (error) {
      ElMessage.error('获取用户详情失败')
      console.error(error)
    }
  }

  // 删除用户
  const handleDeleteUser = async (platformUserId: string | number) => {
    try {
      // 将platformUserId转换为number类型以匹配API接口定义
      const numericPlatformUserId =
        typeof platformUserId === 'string' ? Number(platformUserId) : platformUserId
      const res = await SetupService.userDelete({ platformUserId: numericPlatformUserId })
      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        getUsersList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }

  // 修改用户状态
  const handleStatusChange = async (row: any) => {
    // 保存原始状态，用于失败时恢复
    const originalState = row.state === 1 ? 0 : 1
    try {
      console.log('修改用户状态')
      const res = await SetupService.userUpdate({
        platformUserId: row.platformUserId,
        state: row.state
      })
      if (res.code !== ApiStatus.success) {
        ElMessage.error(res.message || '修改状态失败')
        // 恢复原状态
        row.state = originalState
      }
    } catch (error) {
      ElMessage.error('修改状态失败')
      // 恢复原状态
      row.state = originalState
      console.error(error)
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!userFormRef.value) return

    try {
      await userFormRef.value.validate()
      submitLoading.value = true

      // 处理roleIds数组，确保只包含纯数字类型
      const processRoleIds = (roleIds: any[]) => {
        return roleIds
          .map(id => {
            // 提取数字ID，处理可能的对象格式
            if (typeof id === 'object' && id !== null && 'roleId' in id) {
              return Number(id.roleId)
            }
            return Number(id)
          })
          .filter(id => !isNaN(id) && isFinite(id))
      }

      let res
      if (isEdit.value) {
        // 编辑用户，不需要传递密码，使用解构赋值排除password字段
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { password, ...updateData } = userForm
        // 构建符合后端要求的更新数据
        const submitData = {
          ...updateData,
          // 确保platformUserId为数字类型
          platformUserId: Number(updateData.platformUserId),
          // state已经是数字类型
          state: updateData.state,
          // 确保roleIds为纯数字数组
          roleIds: processRoleIds(updateData.roleIds || [])
        }
        res = await SetupService.userUpdate(submitData)
      } else {
        // 新增用户，确保字段类型正确
        const submitData = {
          ...userForm,
          // 确保platformUserId为数字类型
          platformUserId: Number(userForm.platformUserId),
          // state已经是数字类型
          state: userForm.state,
          // 确保roleIds为纯数字数组
          roleIds: processRoleIds(userForm.roleIds || [])
        }
        res = await SetupService.userAdd(submitData)
      }

      if (res.code === ApiStatus.success) {
        ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        getUsersList()
      } else {
        ElMessage.error(res.message || (isEdit.value ? '编辑失败' : '新增失败'))
      }
    } catch (error) {
      // 表单验证失败不处理，其他错误处理
      if (error instanceof Error) {
        ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
        console.error(error)
      }
    } finally {
      submitLoading.value = false
    }
  }

  // 对话框关闭时
  const onDialogClosed = () => {
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }
  }
</script>

<style lang="scss" scoped>
  .setup-user-container {
    padding: 20px;

    .search-form {
      padding: 15px;
      margin-bottom: 20px;
      background-color: var(--art-gray-50);
      border-radius: 4px;
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }

    .dialog-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
  }

  // 响应式适配
  $device-notebook: 1600px;
  $device-ipad-pro: 1180px;
  $device-ipad: 800px;
  $device-ipad-vertical: 900px;
  $device-phone: 500px;

  // 平板横屏及更小屏幕
  @media screen and (max-width: #{$device-ipad-pro}) {
    .setup-user-container {
      padding: 10px;

      .search-form {
        padding: 10px;
      }

      .search-form .el-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
      }

      .search-form .el-form-item {
        margin-bottom: 10px;
      }

      .search-form .el-form-item:nth-last-child(1) {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }

  // 平板竖屏及更小屏幕
  @media screen and (max-width: #{$device-ipad-vertical}) {
    .setup-user-container {
      padding: 8px;
    }

    // 调整对话框宽度
    :deep(.el-dialog) {
      width: 90% !important;
      max-width: 500px;
    }
  }

  // 手机屏幕
  @media screen and (max-width: #{$device-phone}) {
    .setup-user-container {
      padding: 5px;

      .search-form .el-input,
      .search-form .el-select {
        width: 100% !important;
      }

      .table-actions {
        flex-direction: column;
        gap: 5px;
      }

      // 调整表格样式，确保内容能正常显示
      :deep(.el-table) {
        font-size: 12px;
      }

      :deep(.el-table__header th),
      :deep(.el-table__body td) {
        padding: 8px 4px;
      }

      // 调整表单元素样式
      :deep(.el-radio-group) {
        display: flex;
        gap: 15px;
      }
    }
  }
</style>
